<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="JAVA,Object clone," />










<meta name="description" content="在Object中有clone()方法protected Object clone() throws CloneNotSupportedException clone()的作用是创建一个该对象的一个副本，并将对象的数据复制到该副本中 根据复制程度的不同，clone可以分为：浅拷贝：使用clone()即为浅拷贝，默认的拷贝方式是复制一个新的原对象，并赋予原对象相同的全局对象的值和引用。即原对象和复制对">
<meta name="keywords" content="JAVA,Object clone">
<meta property="og:type" content="article">
<meta property="og:title" content="Java Object的clone方法">
<meta property="og:url" content="http://yoursite.com/2017/03/07/Java Object的clone方法/index.html">
<meta property="og:site_name" content="SISYPHUSER">
<meta property="og:description" content="在Object中有clone()方法protected Object clone() throws CloneNotSupportedException clone()的作用是创建一个该对象的一个副本，并将对象的数据复制到该副本中 根据复制程度的不同，clone可以分为：浅拷贝：使用clone()即为浅拷贝，默认的拷贝方式是复制一个新的原对象，并赋予原对象相同的全局对象的值和引用。即原对象和复制对">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-03-03T05:14:59.242Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java Object的clone方法">
<meta name="twitter:description" content="在Object中有clone()方法protected Object clone() throws CloneNotSupportedException clone()的作用是创建一个该对象的一个副本，并将对象的数据复制到该副本中 根据复制程度的不同，clone可以分为：浅拷贝：使用clone()即为浅拷贝，默认的拷贝方式是复制一个新的原对象，并赋予原对象相同的全局对象的值和引用。即原对象和复制对">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2017/03/07/Java Object的clone方法/"/>





  <title>Java Object的clone方法 | SISYPHUSER</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">SISYPHUSER</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-word">
          <a href="/word/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-calendar"></i> <br />
            
            word
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2017/03/07/Java Object的clone方法/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Andy">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="SISYPHUSER">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Java Object的clone方法</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-03-07T15:34:40+08:00">
                2017-03-07
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/JAVA/" itemprop="url" rel="index">
                    <span itemprop="name">JAVA</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>在Object中有clone()方法<br>protected Object clone() throws CloneNotSupportedException</p>
<p>clone()的作用是创建一个该对象的一个副本，并将对象的数据复制到该副本中</p>
<p>根据复制程度的不同，clone可以分为：<br><strong>浅拷贝</strong>：使用clone()即为浅拷贝，默认的拷贝方式是复制一个新的原对象，并赋予原对象相同的全局对象的值和引用。即原对象和复制对象的全局引用变量指向的是一个相同的对象空间。<br><strong>深拷贝</strong>：需要自己实现，即将原对象中的全局引用变量指向的对象也复制一份放入复制对象中。</p>
<a id="more"></a>
<p>这两个概念可能不太好理解，可以根据下面的案例来加深理解。</p>
<p>首先明确对Object clone的要求</p>
<ol>
<li>实现Cloneable接口，如果不实现该接口会在clone方法中抛出CloneNotSupportedException异常</li>
<li>需要重写clone方法，clone方法在Object中是protect的，不能被外部访问，需要重写并修改为public的访问权限。</li>
</ol>
<p><em>运行类</em></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">class Test&#123;</span><br><span class="line">    @Test</span><br><span class="line">    public void ttt() throws CloneNotSupportedException &#123;</span><br><span class="line">        A a=new A();</span><br><span class="line">        B b=new B();</span><br><span class="line">        a.setName(&quot;one&quot;);</span><br><span class="line">        a.setB(b);</span><br><span class="line">        b.setAge(1);</span><br><span class="line"></span><br><span class="line">        A ca= (A) a.clone();</span><br><span class="line">        a.setName(&quot;two&quot;);</span><br><span class="line">        a.getB().setAge(2);</span><br><span class="line"></span><br><span class="line">        System.out.print(&quot;a.name=&quot;+a.getName()+&quot;\n&quot;+</span><br><span class="line">        &quot;a.b.age=&quot;+a.getB().getAge()+&quot;\n&quot;+</span><br><span class="line">        &quot;ca.name=&quot;+ca.getName()+&quot;\n&quot;+</span><br><span class="line">        &quot;ca.b.age=&quot;+ca.getB().getAge());</span><br><span class="line">        //打印</span><br><span class="line">        /*</span><br><span class="line">        a.name=two</span><br><span class="line">        a.b.age=2</span><br><span class="line">        ca.name=one</span><br><span class="line">        ca.b.age=2</span><br><span class="line">        */</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">class A implements Cloneable&#123;</span><br><span class="line">    private String name;</span><br><span class="line">    private B b;</span><br><span class="line"></span><br><span class="line">    public String getName() &#123;</span><br><span class="line">        return name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setName(String name) &#123;</span><br><span class="line">        this.name = name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public B getB() &#123;</span><br><span class="line">        return b;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setB(B b) &#123;</span><br><span class="line">        this.b = b;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Object clone() throws CloneNotSupportedException &#123;</span><br><span class="line">        return super.clone();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">class B implements Cloneable&#123;</span><br><span class="line">    private int age;</span><br><span class="line"></span><br><span class="line">    public int getAge() &#123;</span><br><span class="line">        return age;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setAge(int age) &#123;</span><br><span class="line">        this.age = age;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Object clone() throws CloneNotSupportedException &#123;</span><br><span class="line">        return super.clone();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面的案例即为浅拷贝，可以看到ca为a的拷贝对象，但是两个对象的b指向的是同一个B的对象。</p>
<p>进行深拷贝：<br>需要修改A中的clone方法</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">@Override</span><br><span class="line">public Object clone() throws CloneNotSupportedException &#123;</span><br><span class="line">    A o=null;</span><br><span class="line">    o=(A)super.clone();</span><br><span class="line">    if(o.b!=null)&#123;</span><br><span class="line">        o.b=(B)o.b.clone();</span><br><span class="line">    &#125;</span><br><span class="line">    return o;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在test中的打印结果为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">a.name=two</span><br><span class="line">a.b.age=2</span><br><span class="line">ca.name=one</span><br><span class="line">ca.b.age=1</span><br></pre></td></tr></table></figure>
<p>另一种利用序列化来实现对象的深拷贝<br>需要序列化，首先要让A和B都实现Serializable接口<br>在A中添加深拷贝方法</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">public Object deepClone() throws IOException, ClassNotFoundException &#123;</span><br><span class="line">    ByteArrayOutputStream  bo=new ByteArrayOutputStream();</span><br><span class="line">    ObjectOutputStream oo=new ObjectOutputStream(bo);</span><br><span class="line">    oo.writeObject(this);</span><br><span class="line">    ByteArrayInputStream bi=new ByteArrayInputStream(bo.toByteArray());</span><br><span class="line">    ObjectInputStream oi=new ObjectInputStream(bi);</span><br><span class="line">    return oi.readObject();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>该方法先将可序列化对象a写入流中，再将对象从流中读出来重建对象</p>
<p><strong>参考博客：</strong><br><a href="http://www.cnblogs.com/gw811/archive/2012/10/07/2712252.html" target="_blank" rel="noopener">java.lang.Object.clone()分析</a><br><a href="http://blog.csdn.net/bigconvience/article/details/25025561" target="_blank" rel="noopener">Java Object对象之clone方法</a><br><a href="http://yangyangmyself.iteye.com/blog/1050674" target="_blank" rel="noopener">Object的clone()方法、深拷贝、浅拷贝</a></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/JAVA/" rel="tag"># JAVA</a>
          
            <a href="/tags/Object-clone/" rel="tag"># Object clone</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/12/23/Mine/" rel="next" title="简历">
                <i class="fa fa-chevron-left"></i> 简历
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/03/08/基于RxJava的RxBus/" rel="prev" title="基于RxJava的RxBus">
                基于RxJava的RxBus <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.gif"
                alt="Andy" />
            
              <p class="site-author-name" itemprop="name">Andy</p>
              <p class="site-description motion-element" itemprop="description">Something Wrong</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">28</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Andy</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
